package com.ttg.web.service.job.model.impl;

import com.google.common.collect.Lists;
import com.google.common.util.concurrent.ListenableFuture;
import com.ttg.common.annotation.TaskRunMethod;
import com.ttg.common.dto.TaskBaseDTO;
import com.ttg.common.utils.BigDecimalUtils;
import com.ttg.common.utils.DateTimeUtil;
import com.ttg.common.vo.TaskResultVO;
import com.ttg.model.dto.MerchModelTaskDTO;
import com.ttg.model.pojo.ModelMctMonth;
import com.ttg.model.vo.AcctPrimitiveSumVO;
import com.ttg.model.vo.MerchAcctInfoVO;
import com.ttg.model.vo.MerchTradePrimitiveSumVO;
import com.ttg.web.dao.BankAccountPrimitiveDao;
import com.ttg.web.dao.BankPublicMerchTradePrimitiveDao;
import com.ttg.web.dao.ModelMctMonthDao;
import com.ttg.web.juc.TasktemplateHelper;
import com.ttg.web.service.job.JobCommon;
import com.ttg.web.service.job.model.ModelMerchJobService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * Description：
 * Author: chenyou
 * Date: 2025/11/12 16:29
 * Company: ttg
 * Copyright: Copyright (c) 2025
 */
@Service
@TaskRunMethod(value = "saveMerchModelDataByMonthTask")
public class ModelMerchJobServiceImpl extends JobCommon implements ModelMerchJobService {
    @Value("${tlinx.isJuc:false}")
    private volatile Boolean isJuc;//是否启用异步回调
    @Autowired
    private TasktemplateHelper tasktemplateHelper;
    @Autowired
    private ModelMctMonthDao modelMctMonthDao;
    @Autowired
    private BankPublicMerchTradePrimitiveDao merchTradePrimitiveDao;
    @Autowired
    private BankAccountPrimitiveDao accountPrimitiveDao;

    /**
     * 基于原始数据->按月归集商户模型数据
     * @param dto
     */
    @Override
    public TaskResultVO saveModelMerchDataByMonth(TaskBaseDTO dto) {
        dto = getCheckYearAndMonth(dto);
        Integer firstDay = DateTimeUtil.getFirstDayOnMonth(dto.getYear(),dto.getMonth());
        Integer lastDay = DateTimeUtil.getLastDayOnMonth(dto.getYear(),dto.getMonth());
        //基于原始数据->按月归集商户模型数据
        List<String> mctNoList = merchTradePrimitiveDao.getMctNosByMonth(firstDay,lastDay);
        List<List<String>> mctNoPartList = Lists.partition(mctNoList,500);

        //删除原记录
        modelMctMonthDao.deleteByYearAndMonth(dto.getYear(),dto.getMonth());
        List<ListenableFuture<TaskResultVO>> futures = new ArrayList<>();
        List<TaskResultVO> results = new ArrayList<>();
        for(List<String> mctNoPart : mctNoPartList){
            MerchModelTaskDTO taskDTO = new MerchModelTaskDTO();
            taskDTO.setMctNos(mctNoPart);
            if(isJuc){
                futures.add(tasktemplateHelper.submit(this,dto,taskDTO));
            }else {
                TaskResultVO result = saveMerchModelDataByMonthTask(dto,taskDTO);
                results.add(result);
            }
        }
        return taskResult(results,futures,isJuc);
    }

    public TaskResultVO saveMerchModelDataByMonthTask(TaskBaseDTO reqDto,MerchModelTaskDTO dto){
        Integer firstDay = DateTimeUtil.getFirstDayOnMonth(reqDto.getYear(),reqDto.getMonth());
        Integer lastDay = DateTimeUtil.getLastDayOnMonth(reqDto.getYear(),reqDto.getMonth());
        Integer days = DateTimeUtil.daysBetween(String.valueOf(firstDay),String.valueOf(lastDay));
        List<String> mctNos = dto.getMctNos();

        List<MerchAcctInfoVO> mctAcctNoList = merchTradePrimitiveDao.getAcctNoByMctNosAndMonth(firstDay,lastDay,mctNos);
        Map<String,List<MerchAcctInfoVO>> mctAcctMap = mctAcctNoList.stream().collect(Collectors.groupingBy(MerchAcctInfoVO::getMctNo));

        List<MerchTradePrimitiveSumVO> sumVOS = merchTradePrimitiveDao.getMerchTradeInfoByMonth(firstDay,lastDay,mctNos);
        List<ModelMctMonth> modelMctMonths = new ArrayList<>();
        for(MerchTradePrimitiveSumVO mctPrimitiveSumVO: sumVOS){
            ModelMctMonth modelMctMonth = new ModelMctMonth();
            modelMctMonth.setYear(reqDto.getYear());
            modelMctMonth.setMonth(reqDto.getMonth());
            modelMctMonth.setMctNo(mctPrimitiveSumVO.getMctNo());
            modelMctMonth.setMctName("");
            modelMctMonth.setMctCustNo("");
            modelMctMonth.setClsId1(mctPrimitiveSumVO.getClsId1());
            modelMctMonth.setClsId2(mctPrimitiveSumVO.getClsId2());
            modelMctMonth.setLivenessDays(mctPrimitiveSumVO.getLivenessDay());
            modelMctMonth.setAvgDepositAmt(BigDecimalUtils.div(mctPrimitiveSumVO.getTimeAmt(),days,0));//按分计算，不保留小数位
            modelMctMonth.setRepairAmt(mctPrimitiveSumVO.getRepairAmt());
            modelMctMonth.setClearCost(BigDecimalUtils.div(modelMctMonth.getRepairAmt(), modelMctMonth.getAvgDepositAmt(),0));//按分计算，不保留小数位


            //根据账户原始数据的授信,用信标记,按月统计是否为授信，用信商户
            List<MerchAcctInfoVO> acctList = mctAcctMap.get(String.valueOf(mctPrimitiveSumVO.getMctNo()));
            List<Long> acctNos = acctList.stream().map(o -> o.getActNo()).collect(Collectors.toList());
            if(acctNos!=null&&acctNos.get(0)!=null){
                List<AcctPrimitiveSumVO> sumVOS1 = accountPrimitiveDao.getAcctInfoByMonth(firstDay,lastDay,acctNos);
                boolean creditFlag = sumVOS1.stream().anyMatch(o -> o.getCreditFlag()>0);
                modelMctMonth.setCreditFlag(creditFlag?"1":"0");
                boolean useCreditFlag = sumVOS1.stream().anyMatch(o -> o.getUseCreditFlag()>0);
                modelMctMonth.setUseCreditFlag(useCreditFlag?"1":"0");
            }
            modelMctMonths.add(modelMctMonth);
        }

        //保存
        modelMctMonthDao.saveBatch(modelMctMonths);
//        modelMctMonthDao.efficientBatchSaveOrUpdate(modelMctMonths);
        return taskReuslt(Status.SUCCESS.getValue(),false,"ok");
    }
}
